﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StudentsManager.Models;
using StudentsManager.Exceptions;
using System.Data.SQLite;

namespace StudentsManager.DataAccess
{
    public class LogDataAccess : DatabaseHelper
    {
        public void AddLog(Log log)
        {
            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();

                var command = new SQLiteCommand("INSERT INTO Logs (Action, Timestamp) VALUES (@Action, @Timestamp)", connection);
                command.Parameters.AddWithValue("@Timestamp", log.Timestamp);
                command.Parameters.AddWithValue("@Action", log.Action);
                command.ExecuteNonQuery();
            }
        }

        public List<Log> GetLogs()
        {
            return GetLogs(new Log());
        }

        public List<Log> GetLogs(Log log)
        {
            List<Log> logs = new List<Log>();

            using (var connection = new SQLiteConnection(_connectionString))
            {
                connection.Open();

                if (log.Action == null)
                {
                    string query = "SELECT * FROM Logs";
                    var command = new SQLiteCommand(query, connection);
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        logs.Add(new Log
                        {
                            Id = Convert.ToInt32(reader["Id"]),
                            Timestamp = Convert.ToDateTime(reader["Timestamp"]),
                            Action = reader["Action"].ToString()
                        });
                    }
                }
                else
                {
                    // 根据Action中的关键词模糊匹配Action字段
                    string query = "SELECT * FROM Logs WHERE Action LIKE @Action";
                    var command = new SQLiteCommand(query, connection);
                    command.Parameters.AddWithValue("@Action", $"%{log.Action}%");
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        logs.Add(new Log
                        {
                            Id = Convert.ToInt32(reader["Id"]),
                            Timestamp = Convert.ToDateTime(reader["Timestamp"]),
                            Action = reader["Action"].ToString()
                        });
                    }
                }
            }

            return logs;
        }
    }
}
